﻿namespace Numbrella.ProblemProvider
{
	using System;
	using System.ComponentModel;
	using System.Windows;

	internal class ProblemDataProvider : INotifyPropertyChanged
	{
		private readonly ProblemProvidingEngine problemProvider;

		public ProblemDataProvider()
		{
			// To support visual designers, which use their own application objects
			if (Application.Current is App)
			{
				this.problemProvider = ((App) Application.Current).ProblemProvider;
				this.problemProvider.ProblemInformationChanged += this.OnProblemInformationChanged;
			}
		}

		public event PropertyChangedEventHandler PropertyChanged;

		public string ProblemName
		{
			get { return this.IsDataAvailable ? this.problemProvider.CurrentProblem.Name : String.Empty; }
		}

		public string ProblemDescription
		{
			get { return this.IsDataAvailable ? this.problemProvider.CurrentProblem.Description.Text : String.Empty; }
		}

		public int PercentageComplete
		{
			get
			{
				return this.IsDataAvailable
				       	? 100 * this.problemProvider.CurrentProblem.CompletedTaskCount /
				       	  this.problemProvider.CurrentProblem.TaskCount
				       	: 0;
			}
		}

		public bool IsDataAvailable
		{
			get { return this.problemProvider != null && this.problemProvider.CurrentProblem != null; }
		}

		private void OnProblemInformationChanged(object sender, EventArgs e)
		{
			this.RaisePropertyChanged(new PropertyChangedEventArgs("ProblemName"));
			this.RaisePropertyChanged(new PropertyChangedEventArgs("ProblemDescription"));
			this.RaisePropertyChanged(new PropertyChangedEventArgs("PercentageComplete"));
			this.RaisePropertyChanged(new PropertyChangedEventArgs("IsDataAvailable"));
		}

		private void RaisePropertyChanged(PropertyChangedEventArgs e)
		{
			PropertyChangedEventHandler handler = this.PropertyChanged;
			if (handler != null) handler(this, e);
		}
	}
}